package com.jandan.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.jandan.logic.JWordzFacade;
import com.jandan.ui.model.CnAndSentence;
import com.jandan.ui.model.Word;

/**
 * 
 * 用于处理浏览词库的ajax请求，请求路径在json-servlet.xml中配置，关于所使用的json处理包，参见相关文档
 * 用于客户端
 * @author Gong Yong
 * @version 1.0
 *
 */
public class WordLibBrowserController implements Controller {
	private JWordzFacade jwordz;

	public void setJwordz(JWordzFacade jwordz) {
		this.jwordz = jwordz;
	}
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		long wordLibID = Long.parseLong(request.getParameter("wordLibID"));
		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));
		
		List<Word> words = jwordz.getWordListByWordLibID(wordLibID,start,limit);
		int count = jwordz.getTotalWordCountOfWordLib(wordLibID);
		
		Map model = new HashMap();
		model.put("totalCount", count);
		ArrayList list = new ArrayList();

		Iterator<Word> it = words.iterator();
		
		Word word = null;
		Map map = null;
		StringBuffer wordCn = null;
		StringBuffer sentences = null;
		StringBuffer details = null;
		List<CnAndSentence> csList = null;
		CnAndSentence cs = null;
		String c = null;
		String s = null;

		while (it.hasNext()) {
			word = it.next();
			map = new HashMap();
			map.put("wordID", word.getWordID());
			map.put("wordEn", word.getWordEn());
			map.put("phonetics", word.getPhonetics());

			wordCn = new StringBuffer();
			sentences = new StringBuffer();
			details = new StringBuffer();
			csList = word.getCnAndSentenceList();

			for (int i = 0, n = csList.size(); i < n; i++) {
				cs = csList.get(i);
				if (cs != null) {
					wordCn.append(cs.getCn());
					wordCn.append(";");;

					c = cs.getCn();
					s = cs.getSentence();

					sentences.append(s);
					sentences.append("#");
					
					if (s != null && s.trim().length() > 0
							&& !s.trim().equalsIgnoreCase("none")) {
						details.append(c);
						details.append("|");
						details.append(s);
						details.append(i != n - 1 ? "|" : "");
					}
				}
			}
			map.put("wordCn", wordCn.toString());
			map.put("details", details.toString());
			map.put("sentences", sentences);
			list.add(map);
		}
		model.put("words", list);
		return new ModelAndView("jsonView", model);
	}
}
